import { useThrottleFn } from '@vueuse/core'
import { getInstanceById } from 'echarts'
import { defineStore } from 'pinia'
import { reactive } from 'vue'

export const useChartsStore = defineStore('charts', () => {
  const charts = reactive<Record<string, string>>({})

  const addChart = (name: string, chartId: string) => (charts[name] = chartId)

  const resizeAllCharts = () => Object.values(charts).forEach((chartId: string) => getInstanceById(chartId)?.resize())

  const throttledResizeAllCharts = useThrottleFn(resizeAllCharts, 500)

  const disposeAllCharts = () => {
    Object.entries(charts).forEach(([, chartId]) => getInstanceById(chartId)?.dispose())
    Object.keys(charts).forEach(key => delete charts[key])
  }

  return {
    charts,
    addChart,
    disposeAllCharts,
    throttledResizeAllCharts
  }
})
